import React from 'react'
import { connect } from 'dva'
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import { Page } from 'components'
import LwjTable from 'components/LwjTable/LwjTable'
import {
  statusOrderChangeApply,
  contractChangeType,
  contractChangeBusinessType,
  contractOrderStatus,
} from 'utils/enumConfig'
import { Modal, Button, Form, Input, Menu, Dropdown, Icon, Card, Tag, message } from 'antd'
import CreateModal from './CreateModal'
import AuditModal from './AuditModal'
import ViewModal from './ViewModal'
import moment from 'moment';
import styles from './index.less';
import GeneralFilter from 'components/Filter/GeneralFilter'
import EditModal from './EditModal';
import { showButton } from 'utils/promissionFilter'
import ContractDetailModal from '../../orderList/$state/ContractDetailModal'

const CheckableTag = Tag.CheckableTag;

const table = ({ location, dispatch, orderChangeApply, contractOrders,orderList, app, loading }) => {
  const {
    items,
    pagination,
    currentItem,
    auditModalVisible = false,
    createModalVisible = false,
    viewModalVisible = false,
    contractModalVisible = false,
    queryParam,
    changeType,
    selectedTags,
    record,
    editVisible = false,
    isSub
  } = orderChangeApply

  const {
    items: contractItems,
    currentItem: contractItem,
    contractSelectedRowKeys
  } = contractOrders

  const { user, resources } = app

  const { isShowContractDetailModal, currentContractDetail } = orderList

  const breadcrumbList = [
    {
      title: '订单管理'
    },
    {
      title: '合同变更申请'
    },
  ]

  /**
   * 定义筛选属性 表单相关
   * @type {{filterItems: *[], onFilterChange(*): void}}
   */
  const filterProps = {
    filterItems: [
      {
        type: 'input',
        id: 'contractNum',
        title: '合同号',
        placeholder: '请输入合同号'
      },
      {
        type: 'input',
        id: 'customerName',
        title: '客户姓名',
        placeholder: '请输入客户姓名'
      },
    ],
    onFilterChange(value) {
      dispatch({
        type: 'orderChangeApply/query',
        payload: {
          ...value
        }
      })
    }
  }

  const onView = (record) => {
    dispatch({
      type: 'orderChangeApply/getDetail',
      payload: record
    })
    dispatch({
      type: 'orderChangeApply/openViewModal',
      payload: {}
    })
    dispatch({
      type: 'orderChangeApply/isSub',
      payload: {
        isSub: false
      }
    })
  }
  const onSub = (record) => {
    dispatch({
      type: 'orderChangeApply/getDetail',
      payload: record
    })
    dispatch({
      type: 'orderChangeApply/openViewModal',
      payload: {}
    })
    dispatch({
      type: 'orderChangeApply/isSub',
      payload: {
        isSub: true
      }
    })
  }

  const onDelete = (record) => {
    Modal.confirm({
      title: '确定吗？',
      content: '您确定要取消这个变更吗',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'orderChangeApply/cancel',
          payload: {
            id: record.id
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const onEdit = (record) => {
    dispatch({
      type: 'orderChangeApply/clearCurrentItemState'
    })
    dispatch({
      type: 'orderChangeApply/setRecord',
      payload: { record: record }
    })
    dispatch({
      type: 'orderChangeApply/onShow',
      payload: {
        num: record.contractNum
      }
    })
    dispatch({
      type: 'orderChangeApply/setChangeType',
      payload: {
        type: record.contractChangeType
      }
    })
    dispatch({
      type: 'orderChangeApply/showEditModal',
      payload: {}
    })

  }

  const onAudit = (record) => {
    dispatch({
      type: 'orderChangeApply/getDetail',
      payload: record
    })
    dispatch({
      type: 'orderChangeApply/openAuditModal',
      payload: {}
    })
  }

  const onCreate = (e) => {
    dispatch({
      type: 'contractOrders/clearItem',
      payload: {}
    })
    dispatch({
      type: 'orderChangeApply/setChangeType',
      payload: {
        type: e.key
      }
    })
    dispatch({
      type: 'orderChangeApply/onChangeModal',
      payload: {}
    })
  }

  /**
   * 选中标签方法
   * @param {*} tag
   * @param {*} checked
   */
  const handleChange = (tag, checked) => {
    const nextSelectedTags = checked ?
      [...selectedTags, tag] :
      selectedTags.filter(t => t !== tag);
    dispatch({
      type: 'orderChangeApply/queryBySelectedTags',
      payload: {
        selectedTags: nextSelectedTags
      }
    });
  };

  /**
   * 重置标签方法
   */
  const resetSelectTags = () => {
    dispatch({
      type: 'orderChangeApply/queryBySelectedTags',
      payload: {
        selectedTags: []
      }
    });
  };

  const onShowContractDetail = (record) => {
    dispatch({
      type: 'orderList/onShowContractDetail',
      payload: {
        contractOrderId: record.contractOrderId,
        salesOrderId: record.salesOrderId
      }
    })
  }

  const contractDetailModalProps = {
    title: '合同详情',
    visible: isShowContractDetailModal,
    destroyOnClose: true,
    width: 1000,
    currentContractDetail,
    footer: null,
    onCancel(record) {
      dispatch({
        type: 'orderList/hideContractDetailModal',
        payload: {}
      })
    },
    showOrderQuote: showButton('contractDetail.orderQuoteSummary', resources, user),
  }

  /** @namespace record.consigneeName */
  /** @namespace record.consigneePhoneNum */
  /** @namespace record.customerName */
  /** @namespace record.customerPhoneNum */
  /**
   * Table的Props
   * @type {{dataSource: *, pagination: *, columns: *[]}}
   */
  const tableProps = {
    dataSource: items,
    pagination: pagination,
    loading: loading.effects['orderChangeApply/query'],
    pageChangeAction: 'orderChangeApply/query',
    dispatch,
    location,
    columns: [
      {
        title: '序号',
        key: 'index',
        render: (text, record, index) => (
          <span>
            {index + 1}
          </span>
        )
      }, {
        title: '合同号',
        dataIndex: 'contractNum',
        key: 'contractNum',
        render: (text, record) => (
          <span>
          <a className={styles.a} onClick={() => onShowContractDetail(record)}>{record.contractNum}</a>
          <Button
            onClick={() => onShowContractDetail(record)}
            size="small"
            shape="circle"
            icon="search"
            style={{ marginLeft: 5 }} />
        </span>
        )
      }, {
        title: '变更类型',
        dataIndex: 'contractChangeType',
        key: 'contractChangeType',
        render: (text, record) => (
          <span>
            {contractChangeType[text]}
          </span>
        )
      }, {
        title: '客户',
        dataIndex: 'customerName',
        key: 'customerName',
        render: (text, record) => (
          <span>
            {record.customerName}/{record.customerPhoneNum}
          </span>
        )
      }, {
        title: '收货人',
        dataIndex: 'consigneeName',
        key: 'consigneeName',
        render: (text, record) => (
          <span>
            {record.consigneeName}/{record.consigneePhoneNum}
          </span>
        )
      }, {
        title: '门店',
        dataIndex: 'salesDistributorName',
        key: 'salesDistributorName',
      }, {
        title: '合同状态',
        dataIndex: 'contractOrderStatus',
        key: 'contractOrderStatus',
        render: (text, record) => (
          <span>
            {contractOrderStatus[text]}
          </span>
        ),
      }, {
        title: '申请单状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record) => (
          <span>
            {statusOrderChangeApply[text]}
          </span>
        ),
      }, {
        title: '申请人',
        dataIndex: 'creatorName',
        key: 'creatorName',
      }, {
        title: '申请时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render: (text, record, index) => (moment(text).format("YYYY-MM-DD HH:mm:ss"))
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          record.status === 'TO_AUDIT' && showButton('orderChangeApply.audit', resources, user) ? <span><a onClick={() => onAudit(record)}> 审核 </a></span> :
            record.status === 'DRAFT' ? <div><span><a
              onClick={() => onEdit(record)}> 编辑 </a></span>
              <span><a
                onClick={() => onSub(record)}> 提交 </a></span>
              <span><a
                onClick={() => onDelete(record)}> 取消 </a></span>
            </div> : <span><a
              onClick={() => onView(record)}> 查看 </a></span>
        )
      }
    ]
  }

  const createModalProps = {
    title: '合同变更',
    visible: createModalVisible,
    onOk: (data) => {
      if (Object.keys(data).length === 1) {
        message.warning('请选择一份合同')
        return
      }
      dispatch({
        type: 'orderChangeApply/store',
        payload: data
      })
      setTimeout(() => {
        dispatch({
          type: 'orderChangeApply/query',
          payload: {}
        })
      }, 1000)
    },
    confirmLoading: false,
    onCancel: () => {
      dispatch({
        type: 'orderChangeApply/hideModal',
        payload: {}
      })
    },
    destroyOnClose: true,
    width: 1200,
    dispatch,
    queryParam,
    contractItems,
    contractModalVisible,
    contractSelectedRowKeys,
    contractItem,
    changeType,
  }

  const auditModalProps = {
    title: '申请合同变更',
    visible: auditModalVisible,
    confirmLoading: false,
    currentItem: currentItem,
    destroyOnClose: true,
    width: 1200,
    footer: false,
    dispatch,
    onCancel: () => {
      dispatch({
        type: 'orderChangeApply/hideModal',
        payload: {}
      })
    }
  }
  const editModalProps = {
    title: '申请合同变更',
    visible: editVisible,
    onCancel: () => {
      dispatch({
        type: 'orderChangeApply/hideModal',
        payload: {}
      })
    },
    record,
    dispatch,
    queryParam,
    contractItems,
    contractModalVisible,
    contractSelectedRowKeys,
    contractItem,
    currentItem,
    changeType,
    width: 1200,
  }

  const viewModalProps = {
    title: '查看合同变更',
    visible: viewModalVisible,
    confirmLoading: false,
    currentItem: currentItem,
    destroyOnClose: true,
    width: 1200,
    footer: false,
    dispatch,
    isSub,
    subDraft: (option) => {
      dispatch({
        type: 'orderChangeApply/subDraft',
        payload: {
          subStatus: option,
          id: currentItem.id,
          version: currentItem.version
        }
      })
    },
    onCancel: () => {
      dispatch({
        type: 'orderChangeApply/hideModal',
        payload: {}
      })
    }
  }

  const menu = (
    <Menu onClick={onCreate}>
      <Menu.Item key="INFORMATION">信息变更</Menu.Item>
      <Menu.Item key="AMOUNT">金额变更</Menu.Item>
    </Menu>
  );

  const statusTagBuilder = () => {
    let tags = []
    Object.keys(statusOrderChangeApply).forEach((key) => {
      tags.push(<CheckableTag
        color="#2db7f5"
        key={key}
        checked={selectedTags.indexOf(key) > -1}
        onChange={checked => handleChange(key, checked)}
      >
        {statusOrderChangeApply[key]}
      </CheckableTag>)
    })

    return tags
  }

  return (
    <PageHeaderLayout title='合同变更申请' breadcrumbList={breadcrumbList}>
      <Page inner>
        <GeneralFilter {...filterProps} />
        <div
          style={{
            textAlign: 'left',
            marginBottom: 20
          }}>
          {showButton('orderChangeApply.apply', resources, user) && <Dropdown overlay={menu}>
            <Button
              type="primary"
              className={styles.card}
            >
              申请合同变更<Icon type="down" />
            </Button>
          </Dropdown>}
        </div>
        <div style={{ marginBottom: 10 }}>
          <Card type="inner">
            <h6 style={{ marginRight: 8, display: 'inline' }}>审核状态:</h6>
            {statusTagBuilder()}
            <Button type="primary" size="small" onClick={() => resetSelectTags()}>重置</Button>
          </Card>
        </div>
        <LwjTable {...tableProps} />
        {createModalVisible && <CreateModal {...createModalProps} />}
        {auditModalVisible && <AuditModal {...auditModalProps} />}
        {viewModalVisible && <ViewModal {...viewModalProps} />}
        {editVisible && <EditModal {...editModalProps} />}
        <ContractDetailModal {...contractDetailModalProps} />
      </Page>
    </PageHeaderLayout>
  )
}

export default connect(({ orderChangeApply, contractOrders, app,orderList, loading }) => ({
  orderChangeApply,
  contractOrders,
  app,
  orderList,
  loading
}))(table)
